package br.com.puertorico.mecanismos.ui.validators;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class EmailValidator implements Validator {

	static final String INVALID_EMAIL_MSG = "Invalid e-mail format.";

	private FacesMessage makeMakeValidateErrorMsg(FacesContext context) {

		Application application;
		String messageText;
		ResourceBundle validationMessages;

		application = context.getApplication();
		validationMessages = ResourceBundle.getBundle(
				application.getMessageBundle(), application.getDefaultLocale());

		try {
			messageText = validationMessages
					.getString("javax.faces.validator.EmailValidator.INVALID");
		} catch (MissingResourceException e) {
			messageText = EmailValidator.INVALID_EMAIL_MSG;
		}
		return new FacesMessage(FacesMessage.SEVERITY_ERROR, messageText,
				messageText);
	}

	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String email = (value != null) ? (String) value : "";
		if (email.isEmpty()) {
			return;
		}

		String emailParts[] = email.split("@");

		if (email.length() < 5 || emailParts.length != 2
				|| !emailParts[1].contains(".")) {
			throw new ValidatorException(this.makeMakeValidateErrorMsg(context));
		}

	}

}
